import sys
import os
import requests
import re
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap, QIcon
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QLabel, QFrame, \
    QLineEdit, QHBoxLayout, QMessageBox
from . import registerDialog
from . import shopping_window
from . import shopping_manage

class LoginWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.ui_init()

    def ui_init(self):
        # 设置窗口图标
        icon = QIcon('./images/购物.png')
        self.setWindowIcon(icon)

        # 设置窗口尺寸
        self.resize(700, 400)
        # 窗口标题
        self.setWindowTitle('登录')

        self.mainLayout = QVBoxLayout(self)

        self.logoLabel = QLabel(self)
        self.logoLabel.setFixedSize(150, 150)  # 设置固定尺寸
        self.logoLabel.setPixmap(QPixmap(os.path.join('images', '购物1.png')))
        self.logoLabel.setScaledContents(True)

        self.formContainer = QFrame()
        formStyleSheet = """
            background-color: white;  /*设置背景颜色*/
            border-radius: 10px;      /*设置圆角弧度*/
            padding: 20px;           /*设置内边距*/
        """
        self.formContainer.setStyleSheet(formStyleSheet)

        self.mainLayout.addWidget(self.logoLabel)
        self.mainLayout.addWidget(self.formContainer)

        # 为mainLayout中控件设置间距
        self.mainLayout.setSpacing(20)
        self.mainLayout.setAlignment(self.logoLabel, Qt.AlignCenter)

        self.formLayout = QVBoxLayout(self.formContainer)
        self.usernameLayout = QHBoxLayout(self)
        self.passwordLayout = QHBoxLayout(self)
        self.buttonLayout = QVBoxLayout(self)
        self.titleLabel = QLabel(self)
        self.titleLabel.setText("密码登录")
        self.titleLabel.setStyleSheet("font-family: 黑体;color: #FF5F00; font-size: 40px; font-weight: bold;")
        self.formLayout.addWidget(self.titleLabel)
        self.formLayout.addLayout(self.usernameLayout)
        self.formLayout.addLayout(self.passwordLayout)
        self.formLayout.addSpacing(30)
        self.formLayout.addLayout(self.buttonLayout)

        inputStyleSheet = """
            padding: 20px;            /*设置内边距  指内容与边框的距离*/
            border: 1px solid #ccc;  /*设置边框宽度  线类型为实线 颜色为灰*/
            border-radius: 5px;    /*设置圆角弧度*/
            font: 30px
        """
        self.usernameInput = QLineEdit(self)
        self.usernameInput.setStyleSheet(inputStyleSheet)
        self.usernameInput.setPlaceholderText("用户名或邮箱")
        self.usernameLayout.addWidget(self.usernameInput)

        self.passwordInput = QLineEdit(self)
        self.passwordInput.setStyleSheet(inputStyleSheet)
        self.passwordInput.setPlaceholderText("密码")
        self.passwordInput.setEchoMode(QLineEdit.Password)
        self.passwordLayout.addWidget(self.passwordInput)

        loginBtnStyleSheet = """
            QPushButton {
                background: #FF5F00;  /*设置背景颜色*/
                color: white;   /*设置文字颜色*/
                font-size: 20px;
                font-weight: bold;
                border-radius: 15px; /*设置边框圆角*/
                padding: 10px;
                min-height: 32px;  /* 高度与注册按钮一致 */
            }
            QPushButton:hover {
                background: #ED4012;  /*设置背景颜色*/
            }
            QPushButton:pressed {
                background: #ED4012;  /*设置背景颜色*/
            }
            QPushButton:disabled {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #ffcc7f, stop:1 #ffa87f);  /* 与注册按钮禁用状态颜色一致 */
                color: white;
                font-size: 20px;
                font-weight: bold;
                border-radius: 15px;
                padding: 10px;
                min-height: 40px;
            }
        """
        registerBtnStyleSheet = """
            QPushButton {
                background: white;  /*设置背景颜色*/
                color: #615F6E;   /*设置文字颜色*/
                font-size: 15px;
                font-weight: bold;
                border-radius: 10px; /*设置边框圆角*/
            }
        """
        # 登录按钮
        self.loginButton = QPushButton(self)
        self.loginButton.setText("登  录")
        self.loginButton.setCursor(Qt.PointingHandCursor)
        self.loginButton.setStyleSheet(loginBtnStyleSheet)
        self.loginButton.clicked.connect(self.login)
        self.passwordInput.returnPressed.connect(self.loginButton.click)

        # 注册按钮
        self.registerButton = QPushButton(self)
        self.registerButton.setFixedSize(100, 20)
        self.registerButton.setText("注  册")
        self.registerButton.setCursor(Qt.PointingHandCursor)
        self.registerButton.setStyleSheet(registerBtnStyleSheet)
        self.registerButton.clicked.connect(self.show_register)

        self.buttonLayout.addWidget(self.loginButton)
        self.buttonLayout.addWidget(self.registerButton, alignment=Qt.AlignRight)

        # 连接 textChanged 信号以更新按钮状态
        self.usernameInput.textChanged.connect(self.update_button_state)
        self.passwordInput.textChanged.connect(self.update_button_state)

        # 初始化按钮状态
        self.update_button_state()

    # 在 LoginWindow 类中添加以下方法
    def clear_inputs(self):
        self.usernameInput.clear()
        self.passwordInput.clear()
    def update_button_state(self):
        username = self.usernameInput.text()
        password = self.passwordInput.text()

        # 验证用户名和密码是否包含至少1个数字
        valid = True
        if not re.search(r'\d', username):
            valid = False
        if not re.search(r'\d', password):
            valid = False

        self.loginButton.setEnabled(valid)

    def show_register(self):
        self.register_dialog = registerDialog.RegisterDialog(self)
        if self.register_dialog.exec_():
            print("注册成功")

    def login(self):
        username = self.usernameInput.text()
        password = self.passwordInput.text()

        # 输入验证：用户名和密码必须包含至少1个数字
        valid = True
        error_messages = []

        if not re.search(r'\d', username):
            error_messages.append("用户名或邮箱必须包含至少1个数字")
            valid = False

        if not re.search(r'\d', password):
            error_messages.append("密码必须包含至少1个数字")
            valid = False

        if not valid:
            QMessageBox.warning(self, "登录错误", "\n".join(error_messages))
            return

        login_url = "http://127.0.0.1:8000/api/auth/login"

        login_data = {
            "username": username,
            "password": password
        }

        try:
            response = requests.post(login_url, json=login_data)
            if response.status_code == 200:
                user_info = response.json()
                print("登录成功！")
                print("用户信息：", user_info)
                self.hide()  # 隐藏登录窗口，而不是关闭
                if user_info["is_admin"] == 0:
                    self.shopping_window = shopping_window.ShoppingWindow(self, user_info)
                    self.shopping_window.show()
                else:
                    # 传递 self 作为 login_widget 给 ShopManage
                    self.shoppingManage_window = shopping_manage.ShopManage(login_widget=self)
                    self.shoppingManage_window.show()
                QMessageBox.information(self, "成功", "登录成功")
            else:
                error_info = response.json()
                print(f"登录失败：{error_info.get('detail', '未知错误')}")
                QMessageBox.information(self, "失败", "登录失败")
        except requests.exceptions.RequestException as e:
            print(f"请求发生错误：{e}")
            QMessageBox.information(self, "请重试", "用户名或密码错误")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = LoginWindow()
    window.show()
    sys.exit(app.exec_())